<?php
namespace app\common\model;
use app\common\model\Base;
use \think\Db;
class ConfigSet extends Base{
	protected $smsRecharge = 'SmsRechargeLog';//短信购买记录表
	protected $configSet = 'configSet';//配置表
	protected $smsEmailSet = 'SmsEmailSet';//邮箱配置表
	protected $smsSet = 'smsSet';//短信配置
	protected $smsTemplate = 'SmsTemplate';//短信模板
	protected $language = 'Language';//语言版本
	protected $webSet = 'WebSet';//网站设置
	protected $serList = 'ServiceList';//服务
	//获取邮箱配置参数
	public function get_email_config(){
		$config = db::connect('database.db_config2')->name($this->configSet)->select();
		foreach($config as $key=>$val){
			$get_config[$val['key']] =$val['value'];
		}
		return $get_config;
	}
	/*
	 * 获取短信配置
	 */
	public function get_sms(){
		$list = db::connect('database.db_config2')->name($this->smsSet)->where(1)->select();
		foreach($list as $k=>$v){
			$result[$v['k']] = $v['v'];
		}
		return $result;
	}
	/**
	 *获取短信条数
	 */
	public function check_sms(){
		$sms_num = db::connect('database.db_config2')->name($this->serList)->where(['web_id'=>config('web_id'),'menu_action'=>7,'status'=>1])->value('times');
		return $sms_num??0;
	}
	/*
	 * 获取短信模板列表
	 */
	public function get_sms_temp($wheresql='1'){
		//短信模板
		$list = db::connect('database.db_config2')->name($this->smsTemplate)->where($wheresql)->select();
		//语言版本
		$lang_list = $this->get_list("is_delete=0");
		foreach($lang_list as $kl=>$vl){
			$language[$vl['id']] = $vl;
		}
		foreach($list as $key => $value){
			$value['type_name'] = '';
			$value['language_name'] = $language[$value['lang_id']]['lang']??'';
			$list[$key] = $value;
		}
		return $list;
	}



	//短信支付
	public function check_sms_info($param){
		$db = $this->db();
		return $db->name($this->smsRecharge)->where(['web_id'=>$param['web_id'],'lang_id'=>$param['lang_id'],'status'=>0,'order_no'=>$param['order_no']])->find();
	}
	//异步回调
	public function pay_return($param,$order_no){
		try{
			$db = $this->db();
			$db->name($this->smsRecharge)->where(['order_no'=>$order_no])->update($param);
		}catch (\Exception $e){
			return false;
		}

	}
	//更改短信条数
	public function change_sms($num,$param){
		try{
			db::connect('database.db_config2')->name($this->webSet)->where(['web_id'=>$param['web_id'],'lang_id'=>$param['lang_id']])->setDec('sms_num',$num);
		}catch (\Exception $e){
			return false;
		}
	}
	/**
	 * 邮件发送函数
	 * @param string $to    接收邮件者邮箱
	 * @param string $subject 邮件主题
	 * @param string $message    邮件内容
	 * @param string $template 模板名
	 * @param string $attachment 附件列表
	 * @param string $ssl  ssl状态
	 * @return boolean
	 */
	public function send_mail($to, $subject = '', $message = '', $template = null , $attachment = null , $ssl = false , $from = null,$param=[]){
		//当没有传邮箱配置参数时检测该站有没有设置
		if(is_null($from)){
			$db = $this->db();
			$is_exit = $db->name($this->smsEmailSet)->where(['web_id'=>config('web_id'),'lang_id'=>config('lang_id')])->find();
			if(empty($is_exit)){
				return ['msg'=>'尚未设置邮箱服务,请设置','status'=>0];
			}
			if($is_exit['is_open'] == 0){
				return ['msg'=>'邮箱服务已关闭,请开启','status'=>0];
			}
		}
		try {
			//$config = C('THINK_EMAIL');
			$mailset = $this->get_email_config();
			//vendor('PHPMailer.class#phpmailer'); //从PHPMailer目录导class.phpmailer.php类文件
			//$mail             = new \PHPMailer(); //PHPMailer对象
			$mail = new \mail\Phpmailer(true);
			$mail->CharSet    = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
			$mail->IsSMTP();  // 设定使用SMTP服务
			$mail->SMTPDebug  = 0;                     // 关闭SMTP调试功能
			// 1 = errors and messages
			// 2 = messages only
			$mail->SMTPAuth   = true;                  // 启用 SMTP 验证功能
			if($ssl) $mail->SMTPSecure = 'ssl';                 // 使用安全协议
			$mail->Host       = $from['smtp']??$mailset['host'];  // SMTP 服务器
			$mail->Port       = $from['port']??$mailset['port'];  // SMTP服务器的端口号
			$mail->Username   = $from['email_account']??$mailset['account'];  // SMTP服务器用户名
			$mail->Password   = $from['pass']??$mailset['password'];  // SMTP服务器密码
			$mail->SetFrom($from['email_account']??$mailset['from_mail'], $from['nickname']??$mailset['from_name']);
			$replyEmail       = isset($mailset['reply_mail'])?$mailset['reply_mail']:$mailset['from_mail'];
			$replyName        = isset($mailset['reply_name'])?$mailset['reply_name']:$mailset['from_name'];
			$mail->AddReplyTo($replyEmail, $replyName);
			$mail->Subject    = $subject;
			if($template){
				$this->assign ( 'message', $message );
				//$message = $this->fetch ( 'Home@Public:sendmail' );
				$message = $this->fetch ( $template );
			}
			$mail->MsgHTML($message);
			$mailTo = explode('|',$to);
			foreach($mailTo as $v){
				$mail->AddAddress($v,'');
			}
			if(is_array($attachment)){ // 添加附件
				foreach ($attachment as $file){
					is_file($file) && $mail->AddAttachment($file);
				}
			}
			$mail->IsHTML(true);
			$mail->Send();
			//debug('end');


			$result['status'] = 1;
			$result['msg'] = '发送成功';
			//$result['time'] = debug('begin','end').'s';
			return $result;
		} catch (\phpmailerException $e) {
			//debug('end');
			$result['status'] = 0;
			$result['msg'] = $e->errorMessage();
			//$result['time'] = debug('begin','end').'s';
			return $result;
		}

	}
	/*
	 * 获取短信发送记录
	 */
	public function get_sms_log($wheresql='1',$order="",$rows="",$field="*"){
		try {
        	$param = \app\common\model\Base::list_param('id','desc');
			$order = $order ?: $param ['sort'] . ' ' . $param ['order'];
			//print_r($param);
			$list['total'] = db('SmsLog')->where($wheresql)->count();
			$list['list'] = db('SmsLog')->where($wheresql)->field($field)->order($order)->page($param['page'],$param['rows'])->select();

			foreach($list['list'] as $key => $value){
				$value['status_name'] = $value['status']==1?'发送成功':'发送失败';
				$value['status_remark'] = $value['status']==1?$value['status_name']:$value['status_name'].": ".$value['remark'];
				$list['list'][$key] = $value;
			}
			$result['status'] = 1;
			$result['data'] = $list;
			return $result;
		} catch (\Exception $e) {
			$result['status'] = 0;
			$result['msg'] = $e;
			return $result;
		}
	}
	
	public function clear_sms_log($where = []){
		$ok = db('SmsLog')->where($where)->delete();
		if($ok){
			$result['msg'] = lang('SUCCESS_DONE');
			$result['status'] = 1;
		}else{
			$result['msg'] = lang('FAIL_DONE');
			$result['status'] = 0;
		}
		return $result;
	}
	/*
	 * 获取邮件发送记录
	 */
	public function get_email_log($wheresql='1',$order="",$rows="",$field="*"){
		$param = grid_param ( 'id','desc'); // 排序及分页参数
		$intkeys = array ('status','id');
		$strkeys = array ();
		$randkeys = array ();
		$likekeys = array ('send_email','from_email','title');
		$inkeys = array();
		$order = $order ?: $param ['sort'] . ' ' . $param ['order'];
		$rows = $rows?:$param['rows'];
		$wheresql .= \app\common\model\Base::buildSearch($intkeys, $strkeys, $randkeys, $likekeys,$inkeys);
		$list = array ();
		$query = input('param.');
		$list = db('EmailLog')->where($wheresql)->order ( $order)->paginate($rows, false, array('query' => $query));

		foreach($list as $key => $value){
			$value['status_name'] = $value['status']==1?lang('SEND_SUCCESS'):lang('SEND_FAIL');
			$value['status_remark'] = $value['status']==1?$value['status_name']:$value['status_name'].": ".$value['remark'];
			$list[$key] = $value;
		}

		return $list;
	}
	/*
	 * 获取邮件发送记录详情
	 */
	public function get_email_log_content($wheresql='1'){
		$one = db('EmailLogContent')->where($wheresql)->find();
		return $one;
	}
	/*
	 * 短信发送记录
	 */
	public function set_sms_log($option, $where = [], $data= []){
		if($option=='del'){
			$ok = db('SmsLog')->where($where)->update($data);
		}else if($option=='add'){
			$ok = db('SmsLog')->insert($data);
		}
		if($ok){
			$result['data'] = $data;
			$result['msg'] = '更新成功';
			$result['status'] = 1;
		}else{
			$result['data'] = [];
			$result['msg'] = '更新失败';
			$result['status'] = 0;
		}
		return $result;
	}
	/*
	 * 编辑邮件发送记录
	 */
	public function set_email_log($option, $where = [], $data= []){
		$mailset = $this->get_email_config();
		$save1 = [
				'web_id' => $data['web_id'],
				'lang_id' => $data['lang_id'],
				'send_address'=>$data['send_address'],
				'from_address'=>$data['from_address']??$mailset['from_mail'],
				'title'=>$data['title'],
				'status'=>$data['status'],
				'remark'=>$data['remark'],
				'addtime'=>$data['addtime'],
				'sendtime'=>$data['sendtime'],
		];
		if($option=='add'){
			$ok1 = db('EmailLog')->insertGetId($save1);
			$save2 = [
					'web_id' => $data['web_id'],
					'lang_id' => $data['lang_id'],
					'id'=>$ok1,
					'content'=>$data['content'],
			];
			$ok2 = db('EmailLogContent')->insert($save2);
		}
		if($ok1){
			$result['data'] = $data;
			$result['msg'] = lang('SUCCESS_DONE');
			$result['status'] = 1;
		}else{
			$result['data'] = [];
			$result['msg'] = lang('FAIL_DONE');
			$result['status'] = 0;
		}
		return $result;
	}

	public function clear_email_log($where = []){
		$ok = db('EmailLog')->where($where)->delete();
		$ok2 = db('EmailLogContent')->where($where)->delete();
		if($ok){
			$result['msg'] = lang('SUCCESS_DONE');
			$result['status'] = 1;
		}else{
			$result['msg'] = lang('FAIL_DONE');
			$result['status'] = 0;
		}
		return $result;
	}
	//获取语言设置
	public function get_list($wheresql='1'){
		$list = db::connect('database.db_config2')->name($this->language)->where($wheresql)->select();
		return $list;
	}

	//短信充值
	public function sms_recharge($param){
		try{
			$db = $this->db();
			$db->name($this->smsRecharge)->insert($param);
		}catch (\Exception $e){
			return false;
		}
	}
	//充值列表
	public function sms_recharge_list($data,$param){
		try{
			$result['unit_price'] = $this->get_sms()['unit_price'];
			$result['list'] = db::name($this->smsRecharge)->field('id,web_id,lang_id,cast(unit_price/100 as decimal(10,2)) as unit_price,num,order_no,cast(price/100 as decimal(10,2)) as price,status,payment_type,cast(total_free/100 as decimal(10,2)) as total_free,addtime,pay_time')
					->where(['web_id'=>$data['web_id'],'lang_id'=>$data['lang_id']])
					->page($param['page'],$param['rows'])
					->order($param['order_str'])
					->select();
			$result['total'] = db::name($this->smsRecharge)
					->where(['web_id'=>$data['web_id'],'lang_id'=>$data['lang_id']])
					->count();
			return $result;
		}catch (\Exception $e){
			return false;
		}
	}
	//获取一条短信
    public function  sms_detail($param){
		try{
			//$result['unit_price'] = $this->get_sms()['unit_price'];
			$result = db::name($this->smsRecharge)->field('id,web_id,lang_id,cast(unit_price/100 as decimal(10,2)) as unit_price,num,order_no,cast(price/100 as decimal(10,2)) as price,status,payment_type,cast(total_free/100 as decimal(10,2)) as total_free,addtime,pay_time')
					->where(['web_id'=>config('web_id'),'lang_id'=>config('lang_id'),'id'=>intval($param['id'])])
					->find();
			return $result;
		}catch (\Exception $e){
			return false;
		}
	}
	//检测短信是否支付轮询
	public function check_sms_pay($param){
		$db = $this->db();
		$status = $db->name($this->smsRecharge)->where(['web_id'=>config('web_id'),'lang_id'=>config('lang_id'),'order_no'=>$param['order_no']])->value('status');
		return ($status ==1)?true:false;
	}
	//邮箱设置
	public function email_set($param){
		try{
			$db = $this->db();
			$where = ['web_id'=>$param['web_id'],'lang_id'=>$param['lang_id']];
			$is_exit = $db->name($this->smsEmailSet)->where($where)->find();
			if(empty($is_exit)){
				$db->name($this->smsEmailSet)->insert($param);
			}else{
				$db->name($this->smsEmailSet)->where($where)->update($param);
			}
		}catch (\Exception $e){
			return false;
		}
	}
	//读取邮箱设置
	public function get_email_set($param,$where){
		try{
			$db = $this->db();
			$res= $db->name($this->smsEmailSet)->where($where)->find();
			if(empty($res)){
				$data = $this->get_email_config();
				$save = [
					'web_id'=>$param['web_id'],
					'lang_id'=>$param['lang_id'],
					'is_open'=>0,
					'email_account'=>$data['account'],
					'pass'=>$data['password'],
					'nickname'=>$data['from_name'],
					'smtp'=>$data['host'],
					'port'=>$data['port'],
					'addtime'=>time(),
				];
				$ok= $db->name($this->smsEmailSet)->insert($save);
				//print_r($data);
				return $save;
			}else{
				return $res;
			}
		}catch (\Exception $e){
			return false;
		}
	}
	/**
	  * 区域缓存
	  */
	public function region_list(){
		$list =  Db::connect(config('database.db_config2'))->name('Region')->where(['status'=>1,'is_delete'=>0])->order("orderid ASC")->field("id,name,pid,pinyin,code")->select();
    	$lists = [];
		foreach($list as $k=>$v){
			$lists[$v['id']] = $v;
		}
		cache( 'region_list', $lists);
		return $lists;
	}

}